﻿using System;
using System.Web.Mvc;
using System.Web.Security;
using ClientApp.Models;
using CommonApp;
using IBS.Model;
using IBS.ServiceContracts;

namespace ClientApp.Controllers
{
    [Authorize]
    public class PrivateController : Controller
    {
        public ActionResult Index()
        {
            var user = Membership.GetUser(User.Identity.Name, true);
            var model = new ChangePrivacyModel();
            model.Email = user.Email;

            return View(model);
        }

        public ActionResult SubmitChanges(ChangePrivacyModel privacy)
        {
            if (ModelState.IsValid)
            {
                MembershipUser currentUser = Membership.GetUser(User.Identity.Name, true);

                // ChangePassword will throw an exception rather
                // than return false in certain failure scenarios.
                bool changePasswordSucceeded = false;
                try
                {
                    if (!currentUser.Email.Equals(privacy.Email))
                    {
                        TempData.AddNotification("Your email has been changed successfully.", "success");
                    }
                    currentUser.Email = privacy.Email;
                    Membership.UpdateUser(currentUser);

                    if (!string.IsNullOrEmpty(privacy.NewPassword) || !string.IsNullOrEmpty(privacy.OldPassword))
                    {
                        changePasswordSucceeded = currentUser.ChangePassword(privacy.OldPassword, privacy.NewPassword);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }

                    if (changePasswordSucceeded)
                    {
                        TempData.AddNotification("Your password has been changed successfully.", "success");
                        return RedirectToAction("Index", "Home");
                    }
                }
                catch (Exception e)
                {
                    
                }
                ModelState.AddModelError("", "Please, ensure to provide valid data to change your password.");
            }

            return View("Index", privacy);
        }
    }
}
